/*
 * CCVisu is a tool for visual graph clustering
 * and general force-directed graph layout.
 * This file is part of CCVisu.
 *
 * Copyright (C) 2005-2011  Dirk Beyer
 *
 * CCVisu is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * CCVisu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with CCVisu; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Please find the GNU Lesser General Public License in file
 * license_lgpl.txt or http://www.gnu.org/licenses/lgpl.txt
 *
 * Dirk Beyer    (firstname.lastname@uni-passau.de)
 * University of Passau, Bavaria, Germany
 */
package org.sosy_lab.ccvisu;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.sosy_lab.common.Files;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.OptionCollector;

import com.google.common.base.Joiner;

public class ConfigurationCreator {

  /**
   * The directory where to look for configuration files for options that get
   * translated into a config file name.
   */
  private static final String DEFAULT_CONFIG_FILES_DIR  = "config/%s.properties";

  private static final String CONFIG_FILE_OPTION = "configuration.file";

  /**
   * Creates an instance of class org.sosy_lab.common.configuration.Configuration
   * based on the array of arguments <code>args</code>.
   * @param args command line arguments
   * @return the configuration
   * @throws InvalidCmdlineArgumentException
   * @throws IOException
   * @throws InvalidConfigurationException
   */
  static Configuration create(String[] args)
      throws InvalidCmdlineArgumentException, IOException,
      InvalidConfigurationException {

    if (args == null || args.length < 1) {
      args = new String[1];
      args[0] = "-gui";
    }

    // if there are some command line arguments, process them
    Map<String, String> cmdLineOptions = processArguments(args);

    // get name of config file (may be null)
    // and remove this from the list of options (it's not a real option)
    String configFile = cmdLineOptions.remove(CONFIG_FILE_OPTION);

    Configuration.Builder config = Configuration.builder();
    if (configFile != null) {
      config.loadFromFile(configFile);
    }
    config.setOptions(cmdLineOptions);

    return config.build();
  }

  /**
   * Reads the arguments and process them.
   * @param args command line arguments
   * @return a map with all options found in the command line
   * @throws InvalidCmdlineArgumentException if there is an error in the
   *         command line
   */
  private static Map<String, String> processArguments(String[] args)
      throws InvalidCmdlineArgumentException {

    Map<String, String> properties = new HashMap<String, String>();
    List<String> inputFiles = new ArrayList<String>();

    Iterator<String> argsIt = Arrays.asList(args).iterator();

    while (argsIt.hasNext()) {
      String arg = argsIt.next();
      if (   handleArgument0("-noout", "output.disable", "true", arg, properties)
          || handleArgument1("-outputpath", "output.path", arg, argsIt, properties)
          || handleArgument1("-logfile", "log.file", arg, argsIt, properties)
          || handleArgument1("-config", CONFIG_FILE_OPTION, arg, argsIt, properties)) {
        // nothing left to do

      } else if (arg.equals("-nolog")) {
        putIfNotExistent(properties, "log.level", "off");
        putIfNotExistent(properties, "log.consoleLevel", "off");

      } else if (arg.equals("-setprop")) {
        if (argsIt.hasNext()) {
          String[] bits = argsIt.next().split("=");
          if (bits.length != 2) { throw new InvalidCmdlineArgumentException(
              "-setprop argument must be a key=value pair!"); }
          putIfNotExistent(properties, bits[0], bits[1]);
        } else {
          throw new InvalidCmdlineArgumentException("-setprop argument missing!");
        }

      } else if (arg.equals("-printOptions")) {
        boolean verbose = false;
        if (argsIt.hasNext()) {
          final String nextArg = argsIt.next();
          verbose = ("-v".equals(nextArg) || ("-verbose".equals(nextArg)));
        }
        System.out.println(OptionCollector.getCollectedOptions(verbose));
        System.exit(0);

      } else if (arg.equals("-printUsedOptions")) {
        putIfNotExistent(properties, "log.usedOptions.export", "true");
        // TODO: CPAchecker, at the moment the only other user of the SoSy-Lab
        // Common lib uses a hack here to stop CPAchecker.  How can we stop
        // CCVisu in the best way?  A first attempt is the System.exit(0),
        // six lines below.

        // this will disable all other output
        properties.put("log.consoleLevel", "OFF");

        // TODO: try to solve the above mentioned issue
        System.exit(0);

      } else if (arg.equals("-version")) {
        System.out.println(InformationProvider.versionMessage());
        System.exit(0);

      } else if (arg.equals("-help") || arg.equals("-h")) {
        printHelp();
        System.exit(0);

      } else if (arg.equals("-gui")) {
        putIfNotExistent(properties, "gui", "true");

      } else if (arg.equals("-assertCheck")) {
        // Check if code is compiled with assertions and terminate CCVisu.
        boolean assertsEnabled = false;
        assert (assertsEnabled = true); // Intentional side effect!
        if (assertsEnabled) {
          System.out.println("Assertions are enabled.");
          System.exit(0);
        } else {
          System.out.println("Assertions are disabled.");
          System.exit(1);
        }

      } else if (arg.startsWith("-") && !(new File(arg).exists())) {
        String argName = arg.substring(1); // remove "-"
        File file = new File(String.format(DEFAULT_CONFIG_FILES_DIR, argName));

        if (argName.matches("^[a-zA-Z0-9-]+$") && file.exists()) {
          try {
            Files.checkReadableFile(file);
            putIfNotExistent(properties, CONFIG_FILE_OPTION, file.getPath());
          } catch (FileNotFoundException e) {
            System.out.println("Invalid configuration " + argName
                + " (" + e.getMessage() + ")");
            System.exit(1);
          }

        } else {
          System.out.println("Invalid option " + arg);
          System.out.println("");
          printHelp();
          System.exit(1);
        }

      } else {
        inputFiles.add(arg);
      }
    }

    // arguments with non-specified options are considered as file names
    if (!inputFiles.isEmpty()) {
      putIfNotExistent(properties, "inputFiles",
          Joiner.on(", ").join(inputFiles));
    }
    return properties;
  }

  private static void printHelp() {
    System.out.println(InformationProvider.versionMessage());
    System.out.println("OPTIONS:");
    System.out.println(" -gui");
    System.out.println(" -config");
    System.out.println(" -outputpath");
    System.out.println(" -logfile");
    System.out.println(" -nolog");
    System.out.println(" -noout");
    System.out.println(" -setprop");
    System.out.println(" -printOptions [-v|-verbose]");
    System.out.println(" -printUsedOptions");
    System.out.println(" -assertCheck");
    System.out.println(" -version");
    System.out.println(" -help");
    System.out.println();
    System.out.println("More information on how to configure CCVisu can be "
        + "found in 'doc/Configuration.txt'.");
  }

  private static void putIfNotExistent(Map<String, String> properties,
      String key, String value)
          throws InvalidCmdlineArgumentException {

    if (properties.containsKey(key)) {
      throw new InvalidCmdlineArgumentException("Duplicate option " + key
          + " specified on command-line");
    }

    properties.put(key, value);
  }

  /**
   * Handle a command line argument with no value.
   */
  private static boolean handleArgument0(String arg, String option,
      String value, String currentArg, Map<String, String> properties)
          throws InvalidCmdlineArgumentException {

    if (currentArg.equals(arg)) {
      putIfNotExistent(properties, option, value);
      return true;
    } else {
      return false;
    }
  }

  /**
   * Handle a command line argument with one value.
   */
  private static boolean handleArgument1(String arg, String option,
      String currentArg, Iterator<String> args, Map<String, String> properties)
          throws InvalidCmdlineArgumentException {

    if (currentArg.equals(arg)) {
      if (args.hasNext()) {
        putIfNotExistent(properties, option, args.next());
      } else {
        throw new InvalidCmdlineArgumentException(currentArg
            + " argument missing!");
      }
      return true;
    } else {
      return false;
    }
  }

  static class InvalidCmdlineArgumentException extends Exception {

    private static final long serialVersionUID = -6526968677815416436L;

    private InvalidCmdlineArgumentException(String msg) {
      super(msg);
    }
  }
}
